package com.springboot.redis.demo.expire;

import com.springboot.redis.demo.RedisClient;

/**
 * 支持超时自动释放的分布式锁案例
 *
 * @author: zr
 * @date: 2021-11-17
 */
public class TimeoutDistributedLockDemo extends RedisClient {

    public static String getKey() {
        return "timeout_lock";
    }

    /**
     * 加锁，并设置超时时间
     *
     * @param key
     * @param value
     * @param timeout
     * @return
     * @throws
     * @date 2021-11-17
     */
    public static boolean lock(String key, String value, int timeout) {
        Long result = jedis.setnx(key, value);
        jedis.expire(key, timeout);
        return result != null ? (result > 0) : false;
    }

    /**
     * 释放锁
     *
     * @param key
     * @return
     * @throws
     * @date 2021-11-17
     */
    public static void unlock(String key) {
        jedis.del(key);
    }

    public static void main(String[] args) throws InterruptedException {
        String key = "lock";
        lock(key, "1", 5);

        boolean lock = lock(key, "1", 5);
        System.out.println("加锁之后，立即重试加锁：" + (lock ? "加锁成功" : "加锁失败"));

        Thread.sleep(6000);

        boolean lock2 = lock(key, "1", 5);
        System.out.println("6秒过后，重试加锁：" + (lock2 ? "加锁成功" : "加锁失败"));
    }
}
